package stack;

import java.util.Stack;

/*
 *@description 逆波兰表达式求值
 *@author hkfan
 *@version 1.0
 *@create 2025/6/6 15:54
 */
public class LeetCode_150 {
    public int evalRPN(String[] tokens) {
        //0. 特殊情况
        if (tokens.length==0){
            return 0;
        }
        //1. 定义
        Stack<Integer> stack = new Stack<>();
        //2. 循环计算
        for (String token : tokens) {
            if (token.equals("+")){
                Integer pop1 = stack.pop();
                Integer pop2 = stack.pop();
                stack.add(pop1+pop2);
            } else if (token.equals("-")) {
                Integer pop1 = stack.pop();
                Integer pop2 = stack.pop();
                stack.add(pop2-pop1);
            } else if (token.equals("*")) {
                Integer pop1 = stack.pop();
                Integer pop2 = stack.pop();
                stack.add(pop1*pop2);
            } else if (token.equals("/")) {
                Integer pop1 = stack.pop();
                Integer pop2 = stack.pop();
                stack.add(pop2/pop1);
            } else {
                stack.add(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }
}
